/**
 * 防抖函数
 * @param fn
 * @param wait time
 * @param immediate 是否立即执行
 * @returns {function(): void}
 */
import {message} from "ant-design-vue";

export function immediatelyDebounce(fn, wait = 1000, immediate = true) {
    let timer;
    return function () {
        if (timer) clearTimeout(timer);
        if (immediate) {
            // 如果已经执行过，不再执行
            let callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait)
            if (callNow) {
                fn.apply(this, arguments)
            }
        } else {
            timer = setTimeout(() => {
                fn.apply(this, arguments)
            }, wait);
        }
    }
}

/**
 * 节流函数
 * @param fn
 * @param wait time
 * @returns {function(): void}
 */
export function throttle(fn, wait = 200) {
    let timer;
    return function () {
        if (!timer) {
            timer = setTimeout(() => {
                timer = null
                fn.apply(this, arguments)
            }, wait)
        }
    }
}

export function dateFormat(date, fmt = 'YYYY-mm-dd HH:MM:SS') {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return fmt;
}


export function copyText(text) {
    let input = document.createElement("input");
    input.value = text
    document.body.appendChild(input);
    input.select()
    document.execCommand('copy')
   message.success('复制成功')
    document.body.removeChild(input);
}
